package com.xueyi.workflow.manager;

import com.xueyi.workflow.event.ProcessStatusChangedEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

/**
 * 流程状态管理器
 * 统一管理流程状态变更和事件发布
 *
 * @author xueyi
 * @date 2024-08-26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProcessStatusManager {
    
    private final ApplicationEventPublisher applicationEventPublisher;
    
    /**
     * 发布流程状态变更事件
     */
    public void publishStatusChangedEvent(Object source, String processInstanceId, String businessKey, 
                                        String processDefinitionKey, String oldStatus, String newStatus, 
                                        String reason, Object additionalData) {
        try {
            ProcessStatusChangedEvent event = new ProcessStatusChangedEvent(
                source, processInstanceId, businessKey, processDefinitionKey, 
                oldStatus, newStatus, reason, additionalData
            );
            
            applicationEventPublisher.publishEvent(event);
            log.info("流程状态变更事件发布成功，processInstanceId: {}, 状态: {} -> {}, 原因: {}", 
                    processInstanceId, oldStatus, newStatus, reason);
                    
        } catch (Exception e) {
            log.error("发布流程状态变更事件失败，processInstanceId: {}", processInstanceId, e);
        }
    }
    
    /**
     * 发布流程状态变更事件（简化版本）
     */
    public void publishStatusChangedEvent(Object source, String processInstanceId, String businessKey, 
                                        String processDefinitionKey, String oldStatus, String newStatus) {
        publishStatusChangedEvent(source, processInstanceId, businessKey, processDefinitionKey, 
                                oldStatus, newStatus, null, null);
    }
    
    /**
     * 发布流程状态变更事件（带原因）
     */
    public void publishStatusChangedEvent(Object source, String processInstanceId, String businessKey, 
                                        String processDefinitionKey, String oldStatus, String newStatus, String reason) {
        publishStatusChangedEvent(source, processInstanceId, businessKey, processDefinitionKey, 
                                oldStatus, newStatus, reason, null);
    }
}
